package com.bingfor.easycablelink.data;

import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;


import com.alibaba.fastjson.JSON;
import com.bingfor.easycablelink.base.BaseActivity;
import com.bingfor.easycablelink.utils.DialogHelp;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;
import rx.functions.Action1;

/**
 * Created by Modificator
 * time: 16-6-23.下午12:57
 * des:create file and achieve model
 */

public class HttpErrorAction implements Action1<Throwable> {

    BaseActivity mContext;
    ReloadCallBack callBack;

    public HttpErrorAction(@NonNull BaseActivity mContext, @NonNull ReloadCallBack callBack) {
        this.mContext = mContext;
        this.callBack = callBack;
    }

    @Override
    public void call(Throwable throwable) {
        AlertDialog.Builder dialog = DialogHelp.getDialog(mContext).setTitle("错误");
        if (throwable instanceof SocketTimeoutException) {
            dialog.setMessage("网络请求超时，请稍后重试");
        } else if (throwable instanceof ConnectException || throwable instanceof UnknownHostException) {
            dialog.setMessage("无法连接到网络，请检查网络后重试");
        } else if (throwable instanceof HttpException && ((HttpException) throwable).code() != 404 && ((HttpException) throwable).code() != 500) {
            HttpException exception = (HttpException) throwable;
            try {
                HttpResult httpResult = JSON.parseObject(exception.response().errorBody().string(), HttpResult.class);
                mContext.showSnakeBar(httpResult.getMsg());
                return;
            } catch (IOException e) {
                e.printStackTrace();
                dialog.setMessage("服务器出问题了，请稍后重试\n错误信息：\n" + throwable.toString());
            }
        } else {
            dialog.setMessage("服信务器出问题了，请稍后重试\\n错误息：\n" + throwable.toString());
        }
        dialog.setCancelable(false)
//                .setPositiveButton("重新加载", (dialogInterface, i) -> callBack.reload())
                .setNegativeButton("取消", null).show();

    }

    public interface ReloadCallBack {
        void reload();
    }
}
